package com.sd.repay.controller;

import com.sd.repay.annotation.MerAuthStatusCheck;
import com.sd.repay.auth.ImplRealAUth;
import com.sd.repay.common.CommonResult;
import com.sd.repay.common.Constants;
import com.sd.repay.pojo.PayOrder;
import com.sd.repay.pojo.RepayPlan;
import com.sd.repay.pojo.WithdrawOrder;
import com.sd.repay.service.*;
import com.sd.repay.utils.JsonUtil;
import com.sd.repay.utils.StringUtil;
import com.sd.repay.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sd on 2018/08/21
 * 统一卡片管理
 */
@Controller
@RequestMapping(value = "/cardMgr")
public class CardManageController {

    private static final Logger log = LoggerFactory.getLogger(CardManageController.class);

    @Autowired
    private MerchantService merchantService;
    @Autowired
    private CardManageService cardManageService;
    @Autowired
    private RepayPlanService planService;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private WithdrawOrderService withdrawOrderService;
    @Autowired
    private MerTokenService merTokenService;

    /**
     * 添加卡片
     *
     * @return
     */
    @MerAuthStatusCheck
    @RequestMapping(value = "/addCardInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public CommonResult addCardInfo(@RequestParam Map<String, String> params) {

        String merchantNo = WebUtil.getCurrMerchantUser().getMerchantNo();
        log.info("商户号[{}]添加卡片参数[{}]", new Object[]{merchantNo, JsonUtil.objectToJson(params)});

        String idCardNo = params.get("idCardNo");
        String mobileNo = params.get("mobileNo");
        String accountNo = params.get("accountNo");
        String accountType = params.get("accountType");
        String province = params.get("province");
        String city = params.get("city");
        String statementDate = params.get("statementDate");
        String repaymentDate = params.get("repaymentDate");

        try {
            if (StringUtil.isBlank(idCardNo, mobileNo, accountNo)) {
                return CommonResult.build(403, "必要参数不能有空值");
            }
            accountType = StringUtils.isBlank(accountType) ? Constants.DEFAULT_ACCOUNT_TYPE_PRIV : accountType;
            params.put("accountType", accountType);

            //校验商户信息
            Map<String, Object> merInfo = merchantService.getMerInfoByMerNo(merchantNo);
            if (null == merInfo || merInfo.isEmpty()) {
                return CommonResult.build(403, "商户不存在");
            }
            String merIdCardNo = String.valueOf(merInfo.get("id_card_no"));
            String realName = String.valueOf(merInfo.get("real_name"));
            if (!idCardNo.equals(merIdCardNo)) {
                return CommonResult.build(403, "身份证号不匹配");
            }

            //校验卡信息
            Map<String, Object> posCardInfo = cardManageService.getPosCardInfoByAccountNo(accountNo);
            log.info(accountNo + "系统卡bin表对应信息：" + JsonUtil.objectToJson(posCardInfo));
            if (null == posCardInfo || posCardInfo.isEmpty()) {
                return CommonResult.build(403, "暂不支持此银行卡");
            }
            String bankName = String.valueOf(posCardInfo.get("bank_name"));
            String cardType = String.valueOf(posCardInfo.get("card_type"));
            String bankNo = String.valueOf(posCardInfo.get("bank_no"));

            if (StringUtil.isBlank(bankName, cardType, bankNo)) {
                return CommonResult.build(403, "暂不支持此银行卡");
            }
            if (!cardType.trim().equals("贷记卡")) {
                return CommonResult.build(403, "只能添加贷记卡");
            }
            Map<String, Object> accCardInfo = cardManageService.getCardManageByAccountNo(accountNo);
            if (null != accCardInfo && !accCardInfo.isEmpty()) {
                return CommonResult.build(403, "此银行卡已添加");
            }

            Map<String, String> authparams = new HashMap<>();
            authparams.put("authType", Constants.AUTH_TYPE_FOUR);
            authparams.put("realName", realName);
            authparams.put("idCardNo", idCardNo);
            authparams.put("accountNo", accountNo);
            authparams.put("mobileNo", mobileNo);
            CommonResult authRes = ImplRealAUth.toRealAuth(authparams);
            if (authRes.getStatus() != 200) {
                return CommonResult.build(403, "银行卡信息与身份信息不匹配");
            }

            cardType = Constants.CARD_TYPE_CREDIT;
            String cardNo = WebUtil.nextUniqueSeqNo("t_card_manage", "", 15);

            params.put("merchantNo", merchantNo);
            params.put("cardNo", cardNo);
            params.put("accountName", realName);
            params.put("cardType", cardType);
            params.put("isSettleCard", "0");
            params.put("settleBankNo", bankNo);
            params.put("bankNo", "");
            params.put("bankName", bankName);

            int saveCount = cardManageService.addCardInfo(params);
            log.info(accountNo + "/" + cardNo + "添加银行卡影响的行数：" + saveCount);
            log.info("商户号[{}]添加信用卡号[{}]影响的行数[{}]", new Object[]{merchantNo, accountNo, saveCount});
            if (saveCount < 1) {
                return CommonResult.build(403, "添加银行卡失败，请稍候再试");
            }
            return CommonResult.ok(cardNo);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("商户号[{}]添加信用卡号[{}]异常[{}]", new Object[]{merchantNo, accountNo, e});
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
    }

    /**
     * 修改卡片
     *
     * @return
     */
    @MerAuthStatusCheck
    @RequestMapping(value = "/updateCardInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public CommonResult updateCardInfo(@RequestParam Map<String, String> params) {

        String merchantNo = WebUtil.getCurrMerchantUser().getMerchantNo();
        log.info("商户号[{}]修改卡片参数[{}]", new Object[]{merchantNo, JsonUtil.objectToJson(params)});

        String accountNo = params.get("accountNo");
        String province = params.get("province");
        String city = params.get("city");
        String statementDate = params.get("statementDate");
        String repaymentDate = params.get("repaymentDate");

        try {
            if (StringUtil.isBlank(accountNo)) {
                return CommonResult.build(403, "必要参数不能有空值");
            }
            Map<String, Object> accCardInfo = cardManageService.getCardManageByAccountNo(accountNo);
            if (null == accCardInfo || accCardInfo.isEmpty()) {
                return CommonResult.build(403, "此银行卡不存在");
            }
            String cardType = String.valueOf(accCardInfo.get("card_type"));
            if (!Constants.CARD_TYPE_CREDIT.equals(cardType)) {
                return CommonResult.build(403, "只能修改信用卡");
            }
            int count = cardManageService.updateCardInfo(accountNo, statementDate, repaymentDate, province, city);
            log.info("商户号[{}]修改银行卡号[{}]信息影响的行数[{}]", new Object[]{merchantNo, accountNo, count});
            return CommonResult.ok();

        } catch (Exception e) {
            e.printStackTrace();
            log.info("商户号[{}]修改银行卡号[{}]异常[{}]", new Object[]{merchantNo, accountNo, e});
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
    }

    /**
     * 删除卡片
     *
     * @param params
     * @return
     */
    @MerAuthStatusCheck
    @RequestMapping(value = "/deleteCard", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public CommonResult deleteCard(@RequestParam Map<String, String> params) {

        String merchantNo = WebUtil.getCurrMerchantUser().getMerchantNo();
        log.info("商户号[{}]删除卡片参数[{}]", new Object[]{merchantNo, JsonUtil.objectToJson(params)});

        try {
            String cardNo = params.get("cardNo");
            if (StringUtils.isBlank(cardNo)) {
                return CommonResult.build(403, "卡片编号不能为空");
            }

            Map<String, Object> cardMapInfo = cardManageService.getCardManageByCardNo(cardNo);
            if (null == cardMapInfo || cardMapInfo.isEmpty()) {
                return CommonResult.build(403, "删除卡片编号不存在");
            }
            String accountNo = String.valueOf(cardMapInfo.get("account_no"));
            String cardType = String.valueOf(cardMapInfo.get("card_type"));
            if (!Constants.CARD_TYPE_CREDIT.equals(cardType)) {
                return CommonResult.build(403, "只能删除信用卡");
            }

            //查询当前卡片是否有执行中的计划
            List<RepayPlan> inExecutePlans = planService.getInExecutePlanByCardNo(cardNo);
            if (!CollectionUtils.isEmpty(inExecutePlans)) {
                return CommonResult.build(403, "有未完成的还款计划，不能删除");
            }

            //查询当前卡片是否有未知状态的交易订单
            List<PayOrder> unEndPayOrders = payOrderService.getUnEndStatusPayOrderByCardNo(cardNo);
            if (!CollectionUtils.isEmpty(unEndPayOrders)) {
                return CommonResult.build(403, "有未完成的交易，不能删除");
            }

            //查询当前卡片是否有未知状态的交代付订单
            List<WithdrawOrder> unEndWithdrawOrders = withdrawOrderService.getUnEndStatusWithdrawOrderByCardNo(cardNo);
            if (!CollectionUtils.isEmpty(unEndWithdrawOrders)) {
                return CommonResult.build(403, "有未完成的交易，不能删除");
            }

            int count = cardManageService.deleteCard(cardNo);
            log.info("商户号[{}]删除卡号[{}]影响的行数[{}]", new Object[]{merchantNo, accountNo, count});
            if (count > 0) {
                merTokenService.deleteTokenByCardNo(cardNo);
            }
            //记录日志
            WebUtil.saveOperateLog(merchantNo, "deleteCard", "t_card_manage", "", "", "删除卡号为" + accountNo + "的信用卡");
            return CommonResult.ok();

        } catch (Exception e) {
            log.error("商户号[{}]异常[{}]", new Object[]{merchantNo, e});
            e.printStackTrace();
            return CommonResult.build(403, "操作失败，请稍候再试");
        }
    }
}
